/**
 * Copyright (c) 2018-2028, HQY 胡庆一 (215218393@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ocm.warehouse.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ocm.core.tool.constant.BladeConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import com.ocm.core.log.exception.ServiceException;
import com.ocm.core.mp.support.Condition;
import com.ocm.core.mp.support.Query;
import com.ocm.core.secure.BladeUser;
import com.ocm.core.tool.api.R;
import com.ocm.core.tool.constant.RoleConstant;
import com.ocm.core.tool.utils.Func;
import com.ocm.core.tool.utils.StringUtil;
import com.ocm.product.entity.Spu;
import com.ocm.product.feign.ISpuClient;
import com.ocm.warehouse.entity.Warehouse;
import com.ocm.warehouse.service.IWarehouseService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ocm.warehouse.entity.Stock;
import com.ocm.warehouse.vo.StockVO;
import com.ocm.warehouse.wrapper.StockWrapper;
import com.ocm.warehouse.service.IStockService;
import com.ocm.core.boot.ctrl.BladeController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 *  控制器
 *
 * @author HQY
 * @since 2021-11-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/stock")
@Api(value = "", tags = "接口")
public class StockController extends BladeController {

	private final IStockService stockService;

	private final IWarehouseService warehouseService;

	private final ISpuClient SpuClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入stock")
	public R<StockVO> detail(Stock stock) {
		Stock detail = stockService.getOne(Condition.getQueryWrapper(stock));
		return R.data(StockWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入stock")
	public R<IPage<StockVO>> list(Stock stock, Query query) {
		IPage<Stock> pages = stockService.page(Condition.getPage(query), Condition.getQueryWrapper(stock));
		return R.data(StockWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入stock")
	public R<IPage<StockVO>> page(@ApiIgnore @RequestParam Map<String, Object> stockVO, Query query,BladeUser bladeUser) {
		if(bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)){
			stockVO.remove("shopId_equal");
		}
		if(stockVO.containsKey("shopId_equal")){
			stockVO.put("shopId_equal",bladeUser.getShopId());
		}
		QueryWrapper<StockVO> q;
		if(stockVO.containsKey("saleAttr")){
			Object o = stockVO.get("saleAttr");
			stockVO.remove("saleAttr");
			q=Condition.getQueryWrapper(stockVO,StockVO.class)
				.eq("s.is_deleted",0)
				.groupBy("s.sku_id")
				.having("sale_attr like '%" + o + "%'");
		}else {
			q=Condition.getQueryWrapper(stockVO,StockVO.class)
				.eq("s.is_deleted",0)
				.groupBy("s.sku_id");
		}

		IPage<StockVO> pages = stockService.selectStockPage(Condition.getPage(query), q);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入stock")
	public R save(@Valid @RequestBody Stock stock,BladeUser bladeUser) {
		if(stockService.count(new QueryWrapper<Stock>().eq("sku_id",stock.getSkuId()))>0){
			return R.fail("该商品已注册仓库");
		}
		R<Spu> res = SpuClient.getSpu(stock.getSpuId());
		if(!res.isSuccess()){
			throw new ServiceException(res.getMsg());
		}
		@NotNull Spu spu = res.getData();
		//判断当前商品是否是本人
		if((spu.getShopId().equals(bladeUser.getShopId())&&stock.getWarehouseId().equals(0L))||StringUtil.containsAny(bladeUser.getRoleName(), RoleConstant.ADMIN))
			return R.status(stockService.save(stock));

		else{
			//仓库用户添加库存无需判断商品归属 判断仓库主人是否为当前用户
			Warehouse w = warehouseService.getById(stock.getWarehouseId());
			if(w.getWarehouseOwner().equals(bladeUser.getUserId())){
				return R.status(stockService.save(stock));
			}
			return R.fail("非法操作");
		}
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入stock")
	public R update(@Valid @RequestBody Stock stock,BladeUser bladeUser) {
		if (stock.getWarehouseId().equals(0L)|| StringUtil.containsAny(bladeUser.getRoleName(), RoleConstant.ADMIN)) {
			stock.setSkuId(null);
			stock.setSpuId(null);
			stock.setStockLock(null);
			return R.status(stockService.updateById(stock));

		} else {
			Warehouse byId = warehouseService.getById(stock.getWarehouseId());
			if (byId.getId().equals(bladeUser.getUserId())) {
				stock.setSkuId(null);
				stock.setSpuId(null);
				stock.setStockLock(null);
				return R.status(stockService.updateById(stock));
			}
			return R.fail("非法操作");
		}
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入stock")
	public R submit(@Valid @RequestBody Stock stock) {
		return R.status(stockService.saveOrUpdate(stock));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(stockService.deleteLogic(Func.toLongList(ids)));
	}


}
